package com.sh169.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.lang.Strings;

import com.sh169.beans.ApplicationConfig;
import com.sh169.beans.UserHolder;
import com.sh169.pojos.User;
import com.sh169.util.BaseHttpFilter;
/**
 *  处理url和角色认证
 *      检查url所需的角色，如为anyone，直接放行
 *      其他: 检查用户角色，如用户为空，将url存入session，重定向到login页面
 *      若不为空： 则检查用户权限是否满足url的角色，若满足放行
 *      不满足 重定向到 无权限页面 403
 * @author Administrator
 *
 */
public class IntecepterFilter extends BaseHttpFilter{
	
	public void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String url = "";
		if(Strings.isEmpty(request.getContextPath()))
			url = request.getRequestURI();
		else
			url = request.getRequestURI().substring(request.getContextPath().length());
		List<String> urlRoles = ApplicationConfig.getRoles4Url(url);
		if(urlRoles == null||urlRoles.size()==0) return ;
		if(urlRoles.contains("anyone")){
			chain.doFilter(request, response);
			return ;
		}
		else{
			UserHolder uh = (UserHolder) request.getSession().getAttribute(SECURITY_SESSION_USER);
			if(uh == null){
				StringBuffer targetUrl = new StringBuffer();
				targetUrl.append(request.getRequestURI());
				if(!Strings.isEmpty(request.getQueryString()))
					targetUrl.append("?").append(request.getQueryString());
				request.getSession().setAttribute(SESSION_TARGET_URL, targetUrl.toString());
				response.sendRedirect(request.getContextPath()+ApplicationConfig.getLogin_uri());
				return ;
			}else{
				List<String> userRoles = uh.getRoles();
				if(userRoles == null||userRoles.size()==0){
					response.sendRedirect(request.getContextPath()+ApplicationConfig.getPage_403());
					return ;
				}else{
					boolean check = false;
					for(String urlRole : urlRoles){
						for(String userRole : userRoles){
							if(urlRole.equals(userRole)){
								check = true;
								break;
							}
						}
						if(check){
							break;
						}
					}
					if(check&&urlRoles.contains("vendor")){
						if(uh.getVendor()==null || uh.getVendor().getVendorState()!=User.STATE_SUCCESS){
							check = false;
						}
					}
					if(check){
						chain.doFilter(request,response);
					}else{
						response.sendRedirect(request.getContextPath()+ApplicationConfig.getPage_403());
						return ;
					}
				}
			}
		}
	}
}
